<?php
namespace app\api\controller;
use app\admin\model\UserAuth;
use app\common\services\RedisService;
use app\common\Tools;
use app\Request;
use think\facade\Db;

/**
 * @Apidoc\Group("用户认证")
 */
class UserAuthController extends ApiBase
{
    /**
     * @Apidoc\Title("个人认证提交")
     * @Apidoc\Url("/api/user_auth/personal")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("name", type="string", require=true, desc="姓名")
     * @Apidoc\Param("idcard", type="string", require=true, desc="身份证号")
     * @Apidoc\Param("idcard_front", type="string", require=true, desc="身份证正面")
     * @Apidoc\Param("idcard_back", type="string", require=true, desc="身份证反面")
     */
    public function personal(Request $request)
        {
            $redis_service = RedisService::getInstance();
            $uid = $this->get_user_id();
            $lock_key = "api:user_auth_personal:" . $uid;

            try {
                $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
                if (!$action_lock) {
                    exception('请勿重复提交认证申请');
                }

                $post_data = $request->postMore([
                    ['name', ''],
                    ['idcard', ''],
                    ['idcard_front', ''],
                    ['idcard_back', ''],
                ]);
                $post_data['type'] = 1;
                $post_data['uid'] = $uid;

                Tools::check($post_data, [
                    'name' => 'require',
                    'idcard' => 'require|idCard',
                    'idcard_front' => 'require|url',
                    'idcard_back' => 'require|url',
                ], [
                    'name.require' => '姓名不得为空',
                    'idcard.require' => '身份证号不得为空',
                    'idcard_front.require' => '身份证正面不得为空',
                    'idcard_back.require' => '身份证反面不得为空',
                ]);

                $exists = UserAuth::where('uid', $uid)->where('type', 1)->find();
                if ($exists && $exists['status'] == 0) {
                    exception('认证正在审核中，请勿重复提交');
                }

                UserAuth::create($post_data);

            } catch (\Exception $e) {
                return app('json')->fail($e->getMessage());

            } finally {
                // 🧹 无论成功与否，释放锁
                $redis_service->releaseLock($lock_key);
            }

            return app('json')->success('提交成功，等待审核');
        }


    /**
     * @Apidoc\Title("企业认证提交")
     * @Apidoc\Url("/api/user_auth/company")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("company_name", type="string", require=true, desc="企业名称")
     * @Apidoc\Param("credit_code", type="string", require=true, desc="信用代码")
     * @Apidoc\Param("license_image", type="string", require=true, desc="营业执照图片")
     * @Apidoc\Param("name", type="string", require=true, desc="法人姓名")
     * @Apidoc\Param("idcard", type="string", require=true, desc="法人身份证号")
     * @Apidoc\Param("idcard_front", type="string", require=true, desc="法人身份证正面")
     * @Apidoc\Param("idcard_back", type="string", require=true, desc="法人身份证反面")
     */
    public function company(Request $request)
    {
        $uid = $this->get_user_id();
        $lockKey = "api:user_auth_company:" . $uid;
        $redis = RedisService::getInstance();

        try {
            return $redis->withLock($lockKey, 5, function () use ($request, $uid) {
                $post_data = $request->postMore([
                    ['company_name', ''],
                    ['credit_code', ''],
                    ['license_image', ''],
                    ['name', ''],
                    ['idcard', ''],
                    ['idcard_front', ''],
                    ['idcard_back', ''],
                ]);

                $post_data['type'] = 2;
                $post_data['uid'] = $uid;

                Tools::check($post_data, [
                    'company_name' => 'require',
                    'credit_code' => 'require',
                    'license_image' => 'require|url',
                    'name' => 'require',
                    'idcard' => 'require|idCard',
                    'idcard_front' => 'require|url',
                    'idcard_back' => 'require|url',
                ], [
                    'company_name.require' => '企业名称不得为空',
                    'credit_code.require' => '统一社会信用代码不得为空',
                    'legal_person.require' => '法人姓名不得为空',
                    'idcard.require' => '法人身份证号不得为空',
                    'business_license.require' => '营业执照图片不得为空',
                    'idcard_front.require' => '身份证正面图片不得为空',
                    'idcard_back.require' => '身份证反面图片不得为空',
                ]);

                $exists = UserAuth::where('uid', $uid)->where('type', 2)->find();
                if ($exists && $exists['status'] == 0) {
                    throw new \Exception('企业认证正在审核中，请勿重复提交');
                }

                UserAuth::create($post_data);
                return app('json')->success('提交成功，等待审核');
            });
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }
    }

}
